//
//  BSCalendarView.swift
//  SBSafetyApp
//
//  Created by Lina on 2022/12/25.
//

import Foundation
import UIKit
import JTAppleCalendar

enum BSCalendarEnum: Int {
    case Default = 991        // 默认
    case Attendance = 992     // 保安考勤统计
    case WorkStatus = 993     // 营业状态修改
    case MonthStatus = 994    // 月营业日修改
    case TaskRate = 995       // 任务完成率
    case TaskRateDetail = 996 // 任务完成率详情
}

protocol BSCalendarViewDelegate: AnyObject {
    func calendar(didSelectDate date: Date)
    func calendar(didViewMonth month: Int, year: Int)
}

class BSCalendarView: UIView {
    weak var delegate: BSCalendarViewDelegate?

    var style: BSCalendarEnum = BSCalendarEnum.Default

    var multipleSelect: Bool = false {
        didSet {
            calendarView.allowsMultipleSelection = multipleSelect
        }
    }
    
    var formatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.timeZone = TimeZone.current
        formatter.dateFormat = "yyyy-MM-dd"
        return formatter
    }()

    let currentCalendar = Calendar.current
    var dateNow = Date()
    var endDate = Date().addingRmoving(years: 3)
    var selectDate = Date()
    
    var ssItems: [StaticsItemModel] = [] // 保安考勤统计
    var yyItems: [YywdModel] = [] // 营业状态修改
    var rateItems: [WclByMonthDateModel] = [] // 任务完成率
    var rwwcxqItems: [RwwcxqModel?] = [] // 任务完成率

    func reload(modals: [StaticsItemModel]) {
        self.ssItems = modals
        calendarView.reloadData()
    }
    
    func reload(withYYItems _items: [YywdModel]) {
        self.yyItems = _items
        calendarView.reloadData()
    }
    
    func reload(withRateItems _items: [WclByMonthDateModel]) {
        self.rateItems = _items
        calendarView.reloadData()
    }
    
    func reload(withRwwcxqs _items: [RwwcxqModel?]) {
        self.rwwcxqItems = _items
        calendarView.reloadData()
    }

    lazy var monthTitleView: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 17)
        label.textColor = .hex("#3F424A")
        return label
    }()

    lazy var leftIndicatorButton: UIButton = {
        let button = UIButton()
        button.setImage(UIImage.init(systemName: "chevron.left"), for: UIControl.State.normal)
        button.addTarget(self, action: #selector(didTapNavigation(sender:)), for: .touchUpInside)
        button.tintColor = .hex("#64676E")
        return button
    }()

    lazy var rightIndicatorButton: UIButton = {
        let button = UIButton()
        button.setImage(UIImage.init(systemName: "chevron.right"), for: UIControl.State.normal)
        button.addTarget(self, action: #selector(didTapNavigation(sender:)), for: .touchUpInside)
        button.tintColor = .hex("#64676E")
        return button
    }()

    lazy var titleStackView: UIView = {
        let view = UIView()
        view.addSubview(leftIndicatorButton)
        view.addSubview(monthTitleView)
        view.addSubview(rightIndicatorButton)
        leftIndicatorButton.snp.makeConstraints { make in
            make.left.equalTo(view).offset(22)
            make.centerY.equalTo(view)
            make.width.equalTo(10)
        }

        monthTitleView.snp.makeConstraints { make in
            make.center.equalTo(view)
        }

        rightIndicatorButton.snp.makeConstraints { make in
            make.width.equalTo(10)
            make.right.equalTo(view).offset(-22)
            make.centerY.equalTo(view)
        }
        return view
    }()

    lazy var weekTitleView: UIStackView = {
        let view = UIStackView()
        view.axis = .horizontal
        view.distribution = .equalSpacing
        let weekStrs = ["日", "一", "二", "三", "四", "五", "六"]

        for weekStr in weekStrs {
            let label = UILabel.createWeekLabel()
            label.text = weekStr
            view.addArrangedSubview(label)
        }
        return view
    }()

    lazy var calendarView: JTACMonthView = {
        let view = JTACMonthView()
        view.backgroundColor = .bg
//        view.translatesAutoresizingMaskIntoConstraints = false
        view.calendarDataSource = self
        view.calendarDelegate = self
        view.scrollDirection = .horizontal
        view.scrollingMode = .stopAtEachSection
        view.minimumInteritemSpacing = 0
        view.minimumLineSpacing = 0
        view.showsHorizontalScrollIndicator = false
        view.showsVerticalScrollIndicator = false
        view.allowsMultipleSelection = multipleSelect
        view.register(BSCalendarCell.self, forCellWithReuseIdentifier: "BSCalendarCell")
        return view
    }()


    init() {
        super.init(frame: .zero)
        calendarView.selectDates([selectDate])
        calendarView.scrollToDate(selectDate, animateScroll: false, preferredScrollPosition: .right)
        monthTitleView.text = "\(dateNow.string(format: "yyyy年MM月"))"

        self.addSubview(titleStackView)
        self.addSubview(weekTitleView)
        self.addSubview(calendarView)

        titleStackView.snp.makeConstraints { make in
            make.top.left.right.equalTo(self)
            make.height.equalTo(48)
        }

        weekTitleView.snp.makeConstraints { make in
            make.left.equalTo(self).offset(22)
            make.right.equalTo(self).offset(-22)
            make.top.equalTo(titleStackView.snp.bottom)
            make.height.equalTo(55)
        }

        calendarView.snp.makeConstraints { make in
            make.left.right.equalTo(self)
            make.top.equalTo(weekTitleView.snp.bottom)
            make.height.equalTo(300)
            make.bottom.equalTo(self)
        }
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    @objc func didTapNavigation(sender: UIButton) {
        if sender == leftIndicatorButton {
            calendarView.scrollToSegment(.previous)
        } else {
            calendarView.scrollToSegment(.next)
        }
    }
}

extension BSCalendarView: JTACMonthViewDataSource, JTACMonthViewDelegate {
    func calendar(_ calendar: JTACMonthView, didScrollToDateSegmentWith visibleDates: DateSegmentInfo) {
        let currentMonth = visibleDates.monthDates.first
        monthTitleView.text = "\(currentMonth?.date.string(format: "yyyy年MM月") ?? "")"
        if currentMonth != nil {
            let month = Calendar.current.component(.month, from: currentMonth!.date)
            let year = Calendar.current.component(.year, from: currentMonth!.date)
            delegate?.calendar(didViewMonth: month, year: year)
            
            if multipleSelect && style == .MonthStatus {
                calendarView.deselectAllDates()
                let first = currentMonth?.date.isSmaller(to: Date()) == true ? Date() : currentMonth!.date
                calendarView.selectDates(from: first, to: visibleDates.monthDates.last!.date)
            }
        }
    }
    
    func configureCalendar(_ calendar: JTACMonthView) -> ConfigurationParameters {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        let startDate = formatter.date(from: "2016-01-01")!
        let parameters = ConfigurationParameters(startDate: startDate,
                                                 endDate: endDate,
                                                 numberOfRows: 6,
                                                 calendar:  Calendar.current,
                                                 generateInDates: .forAllMonths,
                                                 generateOutDates: .tillEndOfGrid)

        return parameters
    }
    
    func calendar(_ calendar: JTACMonthView, willDisplay cell: JTACDayCell, forItemAt date: Date, cellState: CellState, indexPath: IndexPath) {
        (cell as? BSCalendarCell)?.handleCellSelection(cellState: cellState, date: date, selectedDate: selectDate)
    }
    
    func calendar(_ calendar: JTACMonthView, cellForItemAt date: Date, cellState: CellState, indexPath: IndexPath) -> JTACDayCell {
        let myCustomCell = calendar.dequeueReusableCell(withReuseIdentifier: "BSCalendarCell", for: indexPath) as! BSCalendarCell
        myCustomCell.configViews(withStyle: style)
        if style == .Attendance {
            let modals = ssItems.filter({$0.date == date.string(format: "yyyy-MM-dd")})
            if modals.count > 0 {
                myCustomCell.handleCellSelection(cellState: cellState, date: date, selectedDate: selectDate, siModal: modals[0])
                return myCustomCell
            }
        }
        if style == .WorkStatus {
            let modals = yyItems.filter({$0.yyrqStr == date.string(format: "yyyyMMdd")})
            if modals.count > 0 {
                myCustomCell.handleCellSelection(cellState: cellState, date: date, selectedDate: selectDate, yyModal: modals[0])
                return myCustomCell
            }
        }
        
        if style == .MonthStatus {
            myCustomCell.handleCellSelectionDisabled(cellState: cellState, date: date, selectedDate: selectDate)
            return myCustomCell
        }
        
        if style == .TaskRate {
            let modals = rateItems.filter({$0.date == date.string(format: "yyyy-MM-dd")})
            if modals.count > 0 {
                myCustomCell.handleCellSelection(cellState: cellState, date: date, selectedDate: selectDate, ratesModal: modals[0])
                return myCustomCell
            }
        }
        
        if style == .TaskRateDetail {
            let modals = rwwcxqItems.filter({$0?.date == date.string(format: "yyyy-MM-dd")})
            if modals.count > 0 {
                myCustomCell.handleCellSelection(cellState: cellState, date: date, selectedDate: selectDate, rwwcxqModal: modals[0]!)
                return myCustomCell
            }
        }
        
        myCustomCell.handleCellSelection(cellState: cellState, date: date, selectedDate: selectDate)
        return myCustomCell
    }
    
    func calendar(_ calendar: JTACMonthView, didSelectDate date: Date, cell: JTACDayCell?, cellState: CellState, indexPath: IndexPath) {
        selectDate = date
        delegate?.calendar(didSelectDate: date)
        (cell as? BSCalendarCell)?.cellSelectionChanged(cellState, date: date)
    }

    func calendar(_ calendar: JTACMonthView, didDeselectDate date: Date, cell: JTACDayCell?, cellState: CellState, indexPath: IndexPath) {
        (cell as? BSCalendarCell)?.cellSelectionChanged(cellState, date: date)
    }

    func calendar(_ calendar: JTACMonthView, willResetCell cell: JTACDayCell) {
        (cell as? BSCalendarCell)?.selectedView.isHidden = true
    }
}

extension Date {
    func string(format: String) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = format
        return formatter.string(from: self)
    }
}

extension UILabel {
    class func createWeekLabel() -> UILabel {
        let label = UILabel()
        label.textColor = .hex("#B6B6B6")
        label.font = UIFont.systemFont(ofSize: 15)
        return label
    }
}
